import { PREFIX_META,METHOD_META,URL_META,PARAMS_META,HTTPSTATUS_META,SETHEADER_META } from './metadata'

const aa = 'aa'

import Router from 'koa-router'
import 'reflect-metadata'

// controller decorator
export const Controller = (path:string = ''):ClassDecorator => target => Reflect.defineMetadata(PREFIX_META,path,target)

// method decorator
const Method = (method:string) => (url:string):MethodDecorator => {
  return (target,key,descriptor) => {
    Reflect.defineMetadata(METHOD_META,method,descriptor.value)
    Reflect.defineMetadata(URL_META,url,descriptor.value)
  }
}

export const HttpStatus = (code:number = 200) => {
  return (target,key,descriptor) => {
    Reflect.defineMetadata(HTTPSTATUS_META,code,descriptor.value)
  }
}
export const SetHeader = (headers:object) => {
  return (target,key,descriptor) => {
    Reflect.defineMetadata(SETHEADER_META,headers,descriptor.value)
  }
}

// 参数
const Parameter = (type:string,required:boolean = false) => {
  return (name?: string,fn?: Function | undefined) => {
    return (target,method,index) => {
      if(Array.isArray(target.params)){
        target.params.push({ type,name,index,method,required,fn })
      }else{
        target.params = [{ type,name,index,method,required,fn }]
      }
      Reflect.defineMetadata(PARAMS_META,target.params,target,method)
    }
  }
}

const ParameterRequired = (type: string) => {
  const base = Parameter(type)
  const required = Parameter(type,true)
  const ans: any = base
  ans.required = required
  return ans
}

// method
export const Get = Method('get')
export const Post = Method('post')
export const Put = Method('put')
export const Delete = Method('delete')
export const Options = Method('options')
export const Head = Method('head')
export const Patch = Method('patch')

// 参数
export const Ctx = Parameter('ctx')()
export const Next = Parameter('next')()
export const Query = ParameterRequired('query')
export const Body = ParameterRequired('body')
export const Param = ParameterRequired('params')
export const Header = ParameterRequired('headers')
export const Session = ParameterRequired('session')
